package com.qing.design.patterns.proxy.example.some_cool_media_library;

import java.util.HashMap;

public class ThirdPartyYouTubeClass implements ThirdPartyYouTubeLib{


	@Override
	public HashMap<String, Video> popularVideos() {
		connectToServer("http://www.youtube.com");
		return getRandomVideos();
	}

	@Override
	public Video getVideo(String videoId) {
		connectToServer("http://www.youtube.com/" + videoId);
		return getSomeVideo(videoId);
	}


	//--------------------------------------------
	//模拟网络活动的假方法。他们像现实生活一样慢。

	private int random(int min, int max) {
		return min + (int) (Math.random() * ((max - min) + 1));
	}


	//经验
	private void experienceNetworkLatency(){
		int randomLatency=random(5,10);
		for (int i = 0; i < randomLatency; i++) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	private void connectToServer(String server){
		System.out.println("正在连接到"+server);
		experienceNetworkLatency();
		System.out.println("连接成功~！");
	}

	private HashMap<String,Video> getRandomVideos(){
		System.out.println("正在下载populars。。。");
		experienceNetworkLatency();
		HashMap<String, Video> hmap = new HashMap<String, Video>();
		hmap.put("catzzzzzzzzz", new Video("sadgahasgdas", "Catzzzz.avi"));
		hmap.put("mkafksangasj", new Video("mkafksangasj", "Dog play with ball.mp4"));
		hmap.put("dancesvideoo", new Video("asdfas3ffasd", "Dancing video.mpq"));

		System.out.print("已完成!" + "\n");
		return hmap;
	}


	private Video getSomeVideo(String videoId) {
		System.out.print("下载电影。。。");

		experienceNetworkLatency();
		Video video = new Video(videoId, "一些视频标题");

		System.out.print("已完成!" + "\n");
		return video;
	}

}
